package edu.utdallas.cs.securechat.ui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

import edu.utdallas.cs.securechat.main.Client;
import edu.utdallas.cs.securechat.main.Message;

public class LoginDialog extends JDialog implements ActionListener {
	private static final long serialVersionUID = 7673337194122789475L;
	private Client client = null;
	private JTextField jtfuserName;
	private JPasswordField jtfpassword;
	private JButton jbtlogin, jbtexit, jbtnewAccount;
	private String userName;
	private char[] password;
	private boolean success = false;
	private Message registerMessage = null;
	private Message loginMessage = null;
	private ClientFrame owner = null;

	public LoginDialog(final ClientFrame owner) {
		super(owner, "User ID", true);
		this.owner = owner;

		jtfuserName = new JTextField();
		jtfuserName.addActionListener(this);
		jtfpassword = new JPasswordField();
		jtfpassword.addActionListener(this);
		
		client = owner.getClient();
		
		jbtlogin = new JButton("Login");
		jbtlogin.setFocusPainted(false);
		jbtlogin.addActionListener(this);
		jbtexit = new JButton("Exit");
		jbtexit.addActionListener(this);
		jbtexit.setFocusPainted(false);
		jbtnewAccount = new JButton("New Account");
		jbtnewAccount.setHorizontalAlignment(SwingConstants.LEFT);
		jbtnewAccount.setBorderPainted(false);
		jbtnewAccount.setContentAreaFilled(false);
		jbtnewAccount.setBackground(Color.WHITE);
		jbtnewAccount
				.setToolTipText("Never logged in before? Make a new account and start chatting securely!");
		jbtnewAccount.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String username = jtfuserName.getText().trim();
				if (username == null || jtfpassword.getPassword().length == 0 || username.equals("")) {
					showMessage("No field may be left blank!", "Register Failed!", JOptionPane.ERROR_MESSAGE);
					return;
				}
				try {
					registerMessage = client.register(username, jtfpassword.getPassword());
				} catch (Exception ex) {
					ex.printStackTrace();
				}
				if (registerMessage == null) {
					showMessage("Message from server is null! Something is wrong with the network!",
							"Register Failed!", JOptionPane.ERROR_MESSAGE);
					return;
				}
				if (registerMessage.getOperationStatus()) {
					showMessage(registerMessage.getStatusMessage(), "Register Successful!",
							JOptionPane.PLAIN_MESSAGE);
				} else {
					showMessage(registerMessage.getStatusMessage(), "Register Failed!",
							JOptionPane.ERROR_MESSAGE);
				}
			}
		});

		Container pane = getContentPane();
		JPanel panel = new JPanel(new BorderLayout());
		pane.add(panel);

		JPanel labels = new JPanel(new GridLayout(2, 0, 4, 0));
		labels.add(new JLabel("Username"));
		labels.add(new JLabel("Password"));

		JPanel fields = new JPanel(new GridLayout(2, 0, 4, 0));
		fields.add(jtfuserName);
		fields.add(jtfpassword);

		JPanel top = new JPanel(new BorderLayout());
		top.add(labels, BorderLayout.WEST);
		top.add(fields, BorderLayout.CENTER);

		JPanel middle = new JPanel();
		middle.add(jbtnewAccount);

		JPanel bottom = new JPanel();
		bottom.add(jbtlogin);
		bottom.add(jbtexit);

		panel.add(top, BorderLayout.NORTH);
		panel.add(middle, BorderLayout.CENTER);
		panel.add(bottom, BorderLayout.SOUTH);

		pack();
		this.setSize(300, 150);
		this.setResizable(false);
		setLocationRelativeTo(null);
		setVisible(true);
	}

	public void actionPerformed(ActionEvent e) {
		String name = e.getActionCommand();
		if (name.equals("Exit")) {
			success = false;
			setVisible(false);
		} else if (name.equals("Login") || e.getSource() instanceof JTextField) {
			userName = jtfuserName.getText().trim();
			password = jtfpassword.getPassword();
			if (userName.equals("") || password.length == 0) {
				showMessage("No field may be left blank.", "Error Loggin in", JOptionPane.ERROR_MESSAGE);
				return;
			}
			if (userName == null || password == null || !checkLogin(userName, password)) {
				showMessage("Invalid login", "Error logging in", JOptionPane.ERROR_MESSAGE);
				return;
			}
			success = true;
			client.setUserName(userName);
			setVisible(false);
		}
	}

	public boolean login() {
		return success;
	}

	public String getName() {
		return userName;
	}

	public boolean checkLogin(String user, char[] pass) {
		client = owner.getClient();
		try {
			loginMessage = client.login(user, pass);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(loginMessage.getOperationStatus()){
			return true;
		}else{
			return false;
		}
	}

	private void showMessage(String messageBody, String messageTitle, int messageType) {
		JOptionPane.showMessageDialog(this, messageBody, messageTitle, messageType);
	}
}
